

import { phoneCodeLogin, phoneValidCode, qqLoginApi } from '@/pages/home/api'
import { querystring } from '@/utils/authApp';
import { Popup, Toast } from 'antd-mobile'
import { useCountDown} from 'ahooks'
import router from 'next/router';
import { useEffect, useRef, useState } from 'react';
let canClick = true
function Login(props: { onSuccess?: () => void; onClose?: () => void; }) {
    const [visibleLogin, setVisibleLogin] = useState(true)
    const [isAgree,setIsAgree] = useState(true)
    const [phone, setPhone] = useState('')
    const [code, setCode] = useState('')
    const [targetDate, setTargetDate] = useState<number>();
    const [countdown] = useCountDown({
        targetDate,
        onEnd: () => {
            canClick = false
        },
      });
    const changePhoneNumber = (e: React.ChangeEvent<HTMLInputElement>) => { 
        let value = e.target.value
        value = value.replace(/[^\d]/g, '')
        setPhone(value)
    }
    const changeCodeNumber = (e: React.ChangeEvent<HTMLInputElement>) => { 
        let value = e.target.value
        value = value.replace(/[^\d]/g, '')
        setCode(value)
    }
    const getSmsCode = () => { 
        if (!/1[0-9]{10}/.test(phone)) { 
            Toast.show({ content: '请输入正确的手机号' })
            return;
        }
        if (!canClick) return 
        let { authKey } = querystring();
        phoneValidCode({ tel: phone, authKey }).then(res => { 
            if (res.stat === 1) {
                Toast.show({ content: '验证码发送成功' })
                setTargetDate(Date.now() + 60000)
            } else { 
                canClick = true
            }
        })
    }
    const phoneLogin = () => { 
        if (!isAgree) { 
            Toast.show({ content: '需要同意《网络服务使用协议》和《用户隐私条款》' })
            return 
        }
        if (!/1[0-9]{10}/.test(phone) || !/^\d{6}$/.test(code)) { 
            Toast.show({ content: '请输入正确的手机号和验证码' })
            return;
        }
        let { authKey } = querystring();
        phoneCodeLogin({ telNum: phone, telCode: code, visitorAuthKey: authKey }).then(res => { 
            if (res.stat === 1) {
                const { accessToken, authKey } = res.data
                Toast.show({ content: '登录成功' })
                router.replace({
                    pathname: router.pathname,
                    query: {
                        accessToken,
                        authKey
                    }
                })
                localStorage.setItem('userAuth', JSON.stringify({
                    accessToken,
                    authKey,
                    time: Date.now()
                }))
                props.onSuccess && props.onSuccess()
            } else { 
                Toast.show({ content: res.reason })
            }
        }).catch(res => { 
            Toast.show({ content: '登录失败' })
        })
    }

    const qqLogin = () => { 
        let { authKey,accessToken } = querystring();
        qqLoginApi({accessToken,visitorAuthKey:authKey})
    }
    return (
        <Popup
            visible={true}
            onMaskClick={() => {
                
            }}
            // onClose={() => {
            //     props.onClose && props.onClose()
            // }}
            getContainer={() => document.getElementById('h5aiMessage') as HTMLDivElement}
            bodyStyle={{ borderRadius: '5px' }}
        >
            <div className="loginPop">
                <i className='iconfont icon-cuowu' onClick={() => { 
                    props.onClose && props.onClose()
                    // setVisibleLogin(false)
                }}></i>
                <h2>手机验证码登录</h2>
                <p className='item'>
                    <input type="text" placeholder='请输入手机号' onInput={changePhoneNumber} value={phone} />
                </p>
                <p className='item'>
                    <input type="text" value={code} onInput={changeCodeNumber} placeholder='请输入验证码' />
                    <span className={ countdown?'disabled':''} onClick={getSmsCode}>{ countdown?Math.round(countdown/1000)+'后重新获取':'获取验证码'}</span>
                </p>
                <p className='loginBtn' onClick={phoneLogin}>立即登录</p>

                {/* <div className="otherLoginMethod">
                    <span>其他登录方式</span>
                    <strong onClick={qqLogin}>
                        <i className='iconfont icon-QQ'></i>
                        QQ登录
                    </strong>
                    <strong>
                        <i className='iconfont icon-weixin'></i>
                        微信登录
                    </strong>
                </div> */}

                <div className='protocol'>
                    <span onClick={()=>setIsAgree(!isAgree)} className={ 'ckbox ' +(isAgree?'active':'')}></span>
                    <p>
                        我已阅读并同意 <a target='_blank' href="https://818ps.com/page/17">《网络服务使用协议》</a> 和 <a target='_blank' href="https://818ps.com/page/1">《用户隐私条款》</a>
                    </p>
                </div>
            </div>
        </Popup>
    )
}


export default Login